package itbour.onetouchshow;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCustomSignerCredentialProvider;
import com.google.gson.Gson;
import com.itbour.subscriber.ApiFactory;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.net.AppNetConfig;
import com.lsjr.net.DcodeService;
import com.lsjr.utils.HttpUtils;
import com.tencent.smtt.sdk.QbSdk;
import com.three.ConfigAppKey;
import com.three.ThirdConfigManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.video.cut.BaseUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.Semaphore;

import itbour.onetouchshow.base.BaseApplication;
import itbour.onetouchshow.bean.LoginBean;
import itbour.onetouchshow.bean.OssSignBean;
import itbour.onetouchshow.bean.UserDetailInfoBean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.exception.GlobalExceptionHandler;
import itbour.onetouchshow.service.NetworkStateService;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;

/**
 * Created by onetouch on 2017/11/8.
 */

public class App extends Application {

    public static HashMap<String, String> result;
    public static OSSClient ossClient;
    public static Context context = null;
    public static UserDetailInfoBean mUserDetailInfoBean;
    public static boolean initAppInfo = true;
    private static String savePath;
    //秀米数量
    private static double integral;
    QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

        @Override
        public void onViewInitFinished(boolean arg0) {
            //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
            Log.d("app", " onViewInitFinished is " + arg0);
        }

        @Override
        public void onCoreInitFinished() {
        }
    };
    //阿里云存储的字段
    private String accessKeyId;
    //阿里云存储的字段
    private String signature;
    private int mFinalCount;

    public static HashMap getResult() {
        return result;
    }

    public static void setResult(HashMap result) {
        App.result = result;
    }

    public static double getIntegral() {
        return integral;
    }

    public static void setIntegral(double mintegral) {
        integral = mintegral;
    }

    public static LoginBean getLoginBean() {
        String userInfor = SpUtils.getInstance().getString(AppConst.USER_INFO);
        LoginBean loginBean = new Gson().fromJson(userInfor, LoginBean.class);
        if (loginBean == null) {
            try {
                T_.showToastReal("你还没有登陆哟");
                throw new NullPointerException("你还没有登陆哦");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return loginBean;
    }

    public static boolean getUserIsVip() {
        if (mUserDetailInfoBean != null) {
            return mUserDetailInfoBean.getIsVip();
        }
        return false;

    }

    public static void setUserDetailInfoBean(UserDetailInfoBean userDetailInfoBean) {
        mUserDetailInfoBean = userDetailInfoBean;
    }

    public static String getUserId() {
        int userId = getLoginBean().getUserInfo().getUserId();
        return String.valueOf(userId);
    }

    public static void loginOut() {
        SpUtils.getInstance().saveBoolean(AppConst.ISLOGIN, false);
        SpUtils.getInstance().saveString(AppConst.USER_INFO, "");
    }

//    public static HomeDetailslBean getAppInfoBean() {
//        if (appInfoBean == null) {
//            throw new NullPointerException("请重启app");
//        }
//        return appInfoBean;
//    }

    public static boolean isLogin() {
        return SpUtils.getInstance().getBoolean(AppConst.ISLOGIN, false);
    }

    /**
     * 测试时使用
     */
    @SuppressLint("ShowToast")
    public static boolean testWhendebug() {
        return AppConfig.IS_DEBUG_MODULE;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        context = getApplicationContext();
        //初始化存储工具 该工具用于服务器地址选择 因此初始时间比设置baseUrl早
        PreferencesHelper.init(getApplicationContext());
        AppNetConfig.getInstance().setBuider(new AppNetConfig.Builder()
                .setBaseUrl(AppConfig.HTTP_ENCRYPT_BASE)
                .setShareUrl(AppConfig.SHARE).setWebUrl(AppConfig.HTTP_ENCRYPT_ENDDING_WEB));
        //网络变化监听
        startService(new Intent(this, NetworkStateService.class));
        //初始化存储工具
        SpUtils.getInstance().init(App.this);
        DcodeService.initialize(this);
        //新的网络请求设置BaseUrl
        ApiFactory.getFactory().add(AppConfig.HTTP_ENCRYPT_BASE);
        BaseApplication.instance().initialize(this);
        BaseUtils.init(this);
        //注册App是否进入后台
        registerBackCallBack();
        //leakCanary内存泄露检查
        /*LeakCanary.install(this);*/
        L_.init(AppConfig.IS_DEBUG_MODULE, "OneTouchShow");
        //初始化阿里云
        iniAliyun();
        //第三方登录设置App密钥
        ConfigAppKey config = ConfigAppKey.instance().wxId(AppConst.APP_ID).wxSecret(AppConst.APP_SECRET);
        ThirdConfigManager.init(config);
        // 友盟统计
        UMGameAgent.init(this);
        UMGameAgent.setPlayerLevel(1);
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_GAME);
        //禁止默认的页面统计方式，这样将不会再自动统计Activity
        MobclickAgent.openActivityDurationTrack(false);
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
        // AppInitService.startService(this);

        if (!getPacketIsDebug()) {
            //异常捕获
            GlobalExceptionHandler.getInstance().init(this, getResources().getString(R.string.app_name));
        }


        copyAssetAndWrite("msyh.ttf");
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void iniAliyun() {
        // L_.e("初始化阿里云");
        //String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        //阿里云OSS
        OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {

            @Override
            public String signContent(String s) {
                HashMap<String, Object> stringStringHashMap = new HashMap<>();
                stringStringHashMap.put("device", AppConst.ANDROID_DEVICE);
                stringStringHashMap.put("strToSign", s);
                final Semaphore semaph = new Semaphore(0);
                L_.e("初始化阿里云" + AppConfig.GETOSSSIGN_V1_0);
                HttpUtils.getInstance().executeGet(AppConfig.GETOSSSIGN_V1_0, stringStringHashMap, new EncryBeanCallBack() {
                    @Override
                    protected void onXError(String exception) {
                        L_.e("初始化阿里云" + exception);
                        semaph.release(1);

                    }

                    @Override
                    protected void onSuccess(String response) {
                        L_.i("response===" + response);
                        OssSignBean ossSignBean = new Gson().fromJson(response, OssSignBean.class);
                        accessKeyId = ossSignBean.getAccessKeyId();
                        signature = ossSignBean.getSignature();
                        semaph.release(1);
                    }
                });

                try {
                    semaph.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (accessKeyId == null || signature == null) {
                    return null;
                }
                return "OSS " + accessKeyId + ":" + signature;
            }
        };
        ossClient = new OSSClient(getApplicationContext(), AppConfig.ALIYUNCSENDPOINT, credentialProvider);
    }

    private void registerBackCallBack() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mFinalCount++;
                //如果mFinalCount ==1，说明是从后台到前台
                if (mFinalCount == 1) {
                    //说明从后台回到了前台
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mFinalCount--;
                //如果mFinalCount ==0，说明是前台到后台
                Log.i("onActivityStopped", mFinalCount + "");
                if (mFinalCount == 0) {
                    //说明从前台回到了后台
                    PreferencesHelper.saveData(AppConst.KEY_IS_GO_TO_BACKGROUND, true);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private boolean getPacketIsDebug() {
        ApplicationInfo appInfo = null;
        boolean enable = false;
        try {
            appInfo = this.getPackageManager()
                    .getApplicationInfo(getPackageName(),
                            PackageManager.GET_META_DATA);
            enable = appInfo.metaData.getBoolean("isDebug");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return enable;
    }


    /**
     * 将asset文件写入缓存
     */
    private boolean copyAssetAndWrite(String fileName) {
        try {
            File cacheDir = getCacheDir();
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            File outFile = new File(cacheDir, fileName);
            if (!outFile.exists()) {
                boolean res = outFile.createNewFile();
                if (!res) {
                    return false;
                }
            } else {
                if (outFile.length() > 10) {//表示已经写入一次
                    return true;
                }
            }
            InputStream is = getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}


